<?php
  interface iSendAllMsg{
    function getData($url); //curl 发送get请求
    function postData($url,$data); //curl 发送post请求
    function getAccessToken();  //在构造方法中已调用该方法来获取access_token
    function sendMsgToAll($media_id); //群发消息方法,发送的消息$data 可自行修
  }
  class SendAllMsg implements iSendAllMsg{
    private $appId; 
    private $appSecret;
    private $access_token;

	public $title;  	//图文消息标题
	public $img_cover;  //图文消息封面
	public $img_url = array();  //图文消息内容图片组
	
	public $info; 	
	public $content; 	
	
    //
    public function __construct($appId, $appSecret) {
      $this->appId = $appId;
      $this->appSecret = $appSecret;
      $this->access_token = $this->getAccessToken();	  
	  //传入内容
	  $this->title = $_POST['title'];
	  $this->img_cover = $_POST['img'];
	  $this->info = $_POST['info'];
	  $this->content = $_POST['content'];
    }
	//上传图片获取url   图文消息详情中图片地址   返回图片url
	function img_url(){
		$aa = $this->content;
		//var_dump($aa);exit;
		$pattern="/<[img|IMG].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png]))[\'|\"].*?[\/]?>/";
		preg_match_all($pattern,$aa,$match);
		//var_dump($match[1]);exit;
		
		foreach($match[1] as $val){
			$filepath = dirname(__FILE__).$val;	
			$filedata = array("file1"  => "@".$filepath);
			$url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".$this->access_token;
					
			$result = $this->postData($url, $filedata);	
			$result = json_decode($result,true);
			$this->img_url []= $result['url'];	
		}
		 $img = array();
		 foreach($this->img_url as $val){
			 $img []= "img src=\"$val\" /";	
		 }		
		 return $img;
		//return $img_url;  //数组
		//var_dump($img);
	}	
	
	//匹配内容url  转换内容编码
	function cont(){
		
		$aa = $this->content;
		$pattern="/<img.*?src=\"(.*?)\".*?>/i";
		preg_match_all($pattern,$aa,$match);
		$dd = preg_replace($match[0], $this->img_url(), $aa);
		//var_dump($dd);exit;
		//return $dd;
		$dd =urlencode(htmlspecialchars(str_replace("\"","'",$dd)));
		return $dd;
		//var_dump($dd);exit;
	}
	
	
	
	//上传永久图片素材   图文消息封面   返回永久图片media_id   上传多媒体文件接口
	function img_yj(){
		$type = "image";
		$filepath = dirname(__FILE__).$this->img_cover;
		//var_dump($filepath);exit;
		$filedata = array("media"=>"@".$filepath);
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=".$this->access_token."&type=".$type;
		$result = $this->postData($url,$filedata);
		//var_dump($result);exit;
		$result = json_decode($result,true);
		//var_dump($result);exit;
		$media_id_img = $result['media_id'];
		return $media_id_img; 		
		//var_dump($result);
	}
	
		//上传自定义菜单
	function menu(){
		$url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$this->access_token;
		$data = '{
		"button":[{
				   "type":"view",
				   "name":"微官网",
				   "url":"http://www.longling.com"
		  },
		  {
			   "name":"博文欣赏",
			   "sub_button":[
				{
				   "type": "view_limited", 
				   "name": "品味生活", 
				   "media_id": "DNygv52vJzeicockCwLySvjrJNZS8uf1MwOOZIakn-o"
				},
				{
				   "type": "view_limited", 
				   "name": "学海无涯", 
				   "media_id": "DNygv52vJzeicockCwLySurAAfPokaPs2WLBmCxc4WI"
				}]
		   },
		   {
			   "type":"view",
			   "name":"品质白酒",
			   "url":"https://weidian.com/?userid=325305458&wfr=c"
		   }]
		}';
		$this->postData($url,$data);
		
	}
	
	//上传永久图文素材  返回图文素材id 储存到文件media.txt中   群发接口
	function news_material(){
		$url = "https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token=".$this->access_token;  
				
		$data_news ='{
					   "articles": [
							 {
								 "thumb_media_id":"'.$this->img_yj().'",
								 "author":"",
								 "title":"'.$this->title.'",
								 "content_source_url":"http://www.longling.com",
								 "content":"'.$this->cont().'",
								 "digest":"'.$this->info.'",
								 "show_cover_pic":1
							 },
					   ]
					}';				
		//返回html实体	
		$data_news= urldecode($data_news);
		$data_news= htmlspecialchars_decode($data_news);
		$result = $this->postData($url,$data_news);
		$res = json_decode($result,true);
		//var_dump($res);exit;
		$media_id = $res['media_id'];
		file_put_contents('media.txt',$media_id);
		//exit;
		//return $media_id;	
		//var_dump($media_id);
	}

    //get请求
    function getData($url){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt($ch, CURLOPT_HEADER, 0);
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
      curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
      $data = curl_exec($ch);
      curl_close($ch);
      return $data;
    }
    //post请求
    function postData($url,$data){
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_URL, $url);
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
      curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
      curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
      curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
      $tmpInfo = curl_exec($ch);
      if (curl_errno($ch)) {
        return curl_error($ch);
      }
      curl_close($ch);
      return $tmpInfo;
    }
    //获取AccessToken
    function getAccessToken(){
      $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appId."&secret=".$this->appSecret;
      $res = $this->getData($url);
      $jres = json_decode($res,true);
      $access_token = $jres['access_token'];
      return $access_token;
    }
    //获取用户
    private function getUserInfo(){
      $url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=".$this->access_token;
      $res = $this->getData($url);
      $jres = json_decode($res,true);
      //print_r($jres);
      $userInfoList = $jres['data']['openid'];
      return $userInfoList;
	  //var_dump($userInfoList);
    }
	//发送消息
    function sendMsgToAll($media_id){		
      //$userInfoList = $this->getUserInfo();
		//var_dump($userInfoList);exit;
      $url = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token=".$this->access_token;
      $data = '{
				   "filter":{
					  "is_to_all":true,
					   "tag_id":2
				   },
				   "mpnews":{
					  "media_id":"'.$media_id.'"
				   },
					"msgtype":"mpnews"
				}';
       $this->postData($url,$data);
		//var_dump($res);
    }
  }
  $test = new SendAllMsg("wxb4ad47718825d61b","9607857e9d7e7ddd572eded069bca067");
  $test->news_material();
  $media_id = file_get_contents('media.txt');
  $test->sendMsgToall($media_id);
  //$test->menu();
  //$test->cont();
  //$test->img_url();
  //$test->img_yj();  
   
?>